<?php
/**
 * 会员中心--订单页
 *
 * @copyright  Copyright (c) 2007-2013 ShopNC Inc. (http://www.shopnc.net)
 * @license    http://www.shopnc.net
 * @link       http://www.shopnc.net
 * @since      File available since Release v1.1
 */
defined('InShopNC') or exit('Access Invalid!');

class member_orderControl extends MobileControl {
	public function __construct(){
		parent::__construct();
		//检查是否登录
		$this->isLogin();
	}
	
	/**
	 * 全部订单列表
	 */
	public function indexOp() {
        //订单列表
        $this->orderlist();
		//查询会员信息
		$this->get_member_info();
        Tpl::showpage('member_order');
	}

    /**
     *删除定单，不能恢复
     */
    public function ajax_del_orderOp(){
        $order_id = (int)$_GET['order_id'];
        if(empty($order_id)|| !is_numeric($order_id)){
            echo json_encode(array('state'=>false,'msg'=>'删除定单出错，请稍候再试'));
        }
        if(DB::delete('order',"order_id='$order_id'")){
            echo json_encode(array('state'=>true,'msg'=>'删除定单成功'));
        }else{
            echo json_encode(array('state'=>false,'msg'=>'删除定单出错，请稍候再试'));
        }
    }
	
	//订单详情
	public function orderDetailOp(){
		
		$order_id	= intval($_GET['order_id']);
		/**
		 * 实例化订单模型
		 */
		$model_order	=new orderModel();
		$condition['buyer_id'] = $_SESSION['member_id'];
		$condition['order_id'] = $order_id;
		$order_info = $model_order->getOrderById($order_id,'all',$condition);
		$order_id	= intval($order_info['order_id']);
		if($order_id == 0) {
			mobileJump('缺少参数');
		}
        $order_info['state_info'] = orderModel::orderStateInfo($order_info['order_state'],$order_info['refund_state']);
		//$order_info['state_info'] = $this->orderStateInfo($order_info['order_state'],$order_info['refund_state']);
		Tpl::output('order_info',$order_info);
		if(!empty($order_info['group_id']) && is_numeric($order_info['group_id'])){
			$group_name = Model()->table('goods_group')->getfby_group_id($order_info['group_id'],'group_name');
			Tpl::output('group_name',$group_name);
		}
		/**
		 * 卖家信息
		 */
		$model_store	=new storeModel();
		$store_info		= $model_store->shopStore(array('store_id'=>$order_info['store_id']));
		Tpl::output('store_info',$store_info);
		/**
		 * 实例化买家订单模型
		 */
		$model_my_order =new my_orderModel();
		/**
		 * 订单商品
		 */
		$order_goods_list= $model_my_order->myOrderGoodsList(array('order_id'=>$order_id));
		Tpl::output('order_goods_list',$order_goods_list);
		/**
		 * 订单处理历史
		 */
		$log_list	= $model_order->orderLoglist($order_id);
		Tpl::output('order_log',$log_list);
		/**
		 * 实例化退款模型
		 */
		$model_refund	=new refundModel();
		$condition = array();
		$condition['buyer_id'] = $_SESSION['member_id'];
		$condition['order_id'] = $order_id;
		$condition['refund_state'] = '2';
		$condition['order']	=  'log_id asc';
		$refund_list = $model_refund->getList($condition);
		Tpl::output('refund_list',$refund_list);
		/**
		 * 实例化退货模型
		 */
		$model_return	=new returnModel(); 
		$condition = array();
		$condition['buyer_id'] = $_SESSION['member_id'];
		$condition['order_id'] = $order_id;
		$condition['return_state'] = '2';
		$condition['order']	=  'return.return_id asc';
		$return_list= $model_return->getReturnGoodsList($condition);
		Tpl::output('return_list',$return_list);
		/**
		 * 页面输出
		 */
		Tpl::showpage('member_order_detail');
	}
	
	/**
	 * 查看物流
	 *
	 */
	public function show_expressOp() {		
		$order_id	= intval($_GET['order_id']);
		/**
		 * 实例化订单模型
		 */
		$model_order	=new orderModel();
		$condition['buyer_id'] = $_SESSION['member_id'];
		$condition['order_id'] = $order_id;
		$order_info = $model_order->getOrderById($order_id,'all',$condition);

		$order_id	= intval($order_info['order_id']);
		if($order_id == 0) {
			mobileJump('缺少参数');
		}
        $order_info['state_info'] = orderModel::orderStateInfo($order_info['order_state']);
		//$order_info['state_info'] = $this->orderStateInfo($order_info['order_state']);
		Tpl::output('order_info',$order_info);	
		 /**
         * 卖家信息
         */
        $model_store	=new storeModel();
        $store_info		= $model_store->shopStore(array('store_id'=>$order_info['store_id']));
        Tpl::output('store_info',$store_info);
		//取得配送公司代码
		$express_list  = ($h = F('express')) ? $h : H('express',true,'file');

		Tpl::output('e_code',$express_list[$order_info['shipping_express_id']]['e_code']);
		Tpl::output('e_name',$express_list[$order_info['shipping_express_id']]['e_name']);
		Tpl::output('e_url',$express_list[$order_info['shipping_express_id']]['e_url']);

		Tpl::output('shipping_code',$order_info['shipping_code']);
		
		 if($order_info['shipping_mode'] == SHIPPING_MODE_DEFAULT && $order_info['shipping_express_id'] > 0) {
			 Tpl::showpage('member_order_express_detail');
		 }elseif ($order_info['shipping_mode'] == SHIPPING_MODE_MDT || $order_info['shipping_mode'] ==SHIPPING_MODE_FDY){
			if (empty($order_info['shipping_express_id']) && $order_info['order_state'] >= 25) {
				Tpl::showpage('member_order_mdt_express_detail');
			}elseif(!empty($order_info['shipping_express_id']) && ($order_info['order_state'] >= 30||$order_info['order_state'] == 11)){
				Tpl::showpage('member_order_express_detail');
			}
		}
	}

	/**
	 * 从第三方取快递信息
	 *
	 */
	public function get_expressOp(){

		$url = 'http://www.kuaidi100.com/query?type='.$_GET['e_code'].'&postid='.$_GET['shipping_code'].'&id=1&valicode=&temp='.random(4).'&sessionid=&tmp='.random(4);
		import('function.ftp');
		$content = dfsockopen($url);
		$content = json_decode($content,true);
		

		if ($content['status'] != 200) exit(json_encode(false));
		//$content['data'] = array_reverse($content['data']); //手机版和PC版顺序相反
		$len = count($content['data']);
		$i = $len;
		$on = '';
		$output = '';
		if (is_array($content['data'])){
			foreach ($content['data'] as $k=>$v) {
				if ($v['time'] == '') continue;
				$len == $i ? $on = 'on' : $on = '';
				$output .= '<li><span class="icon '.$on.'"></span><span>'.$v['context'].'</span><span>'.$v['time'].'<span></li>';
				$len--;
			}
		}
		if ($output == '') exit(json_encode(false));
		echo json_encode($output);
	}
	
	/*
     * 申请售后
     * */
    public function applysaleOp(){
       order_applysaleModel::selectApplysale();
    }
	
	/**
	 * 售后退款
	 *
	 */
	public function refund_addOp(){
		order_applysaleModel::refundAdd();
		Tpl::showpage('member_refund_add');
	}


	
	/**
	 * 售后退货退款
	 *
	 */
	public function return_addOp(){
		order_applysaleModel::returnAdd();
	}
	
	//仅退款--售后动态
	public function refund_viewOp(){
		order_applysaleModel::refundView();
		Tpl::showpage('member_refund_view');
	}
	


	//退货退款--售后动态
	public function return_viewOp(){
		order_applysaleModel::returnView();
		Tpl::showpage('member_return_view');
	}
	
	/*保存快递单号*/
    public function save_expressOp(){
		order_applysaleModel::returnExpress();
    }
	
	//取消退款申请
    public function refund_cancelOp(){
		order_applysaleModel::refundCancel();
    }
	
	//取消退货退款申请
    public function return_cancelOp(){
		order_applysaleModel::returnCancel();
    }

	
	/**
	 * 买家订单状态操作
	 *
	 */
	public function change_stateOp() {
		$state_type	= trim($_GET['state_type']);
		$order_id	= intval($_GET['order_id']);
		if($state_type == '' || $order_id<=0) mobileJump('参数错误','index.php?act=member_order');
		//实例化订单模型
		$model_order =new orderModel();
		//获取订单详细
		$order	= $model_order->getOrderById($order_id,'simple');
		if (!is_array($order) || empty($order)){
			mobileJump('订单信息错误','index.php?act=member_order');
		}
		//验证订单信息是否属于该会员
		if ($_SESSION['member_id'] != $order['buyer_id']){
			mobileJump('订单所有者错误','index.php?act=member_order');	
		}
		$array	= array();
		switch ($state_type) {
			case 'cancel_order':	//买家取消订单
				$state_code = 0;
			break;
			case 'confirm_order':	//买家确定订单
				$array['finnshed_time'] = time();
				$state_code = 40;
			break;
		}
		//验证订单信息状态是否与更改状态相同
		if (intval($order['order_state']) ==  $state_code){
			mobileJump('订单状态不可重复更改','index.php?act=member_order');
		}
		$array['order_state'] = $state_code;
		//实例化订单模型
		$model_my_order =new my_orderModel();
		$goods_list = $model_my_order->myOrderGoodsList(array('order_id'=>$order_id));
		//取消订单
		if($state_code == 0) {
			db::delete('jky_buy',"order_id='$order_id'");
                            //取消订单返还现金券-Start
                            Db::update('xjq',array('use_amount'=>0,'use_state'=>XJQ_USE_STATE_NO,'use_time'=>0),"xjq_id='{$order['xjq_id']}'");
                            Db::update('order',array('xjq_id'=>0),"order_id='$order_id'");
            memberModel::memberXjqShow($_SESSION['member_id']);
                            //取消订单返还现金券-End
            //***********扣除积分***************
            $points_model =new pointsModel();
            $points_model->kouPointsByOrderID($order_id);
            //**************************
			$model_goods=new goodsModel();
			if(is_array($goods_list) and !empty($goods_list)) {
				foreach ($goods_list as $val) {
                    /*$model_goods->updateSpecStorageGoods(array('spec_goods_storage'=>array('value'=>$val['goods_num'],'sign'=>'increase'),'spec_salenum'=>array('value'=>$val['goods_num'],'sign'=>'decrease')),$val['spec_id']);
$model_goods->updateGoods(array('salenum'=>array('value'=>$val['goods_num'],'sign'=>'decrease')),$val['goods_id']);
*/
                    $goods_specModel=new goods_specModel();
                    $spec_info=$goods_specModel->getOne($val['spec_id']);
                    $update_spec=array();
                    $update_spec['spec_goods_storage']=array('value'=>$val['goods_num'],'sign'=>'increase');
                    if(isset($spec_info['spec_salenum'])&&$spec_info['spec_salenum']>=$val['goods_num']){//避免出现负销售量的情况
                        $update_spec['spec_salenum']=array('value'=>$val['goods_num'],'sign'=>'decrease');
                    }
					$model_goods->updateSpecStorageGoods($update_spec,$val['spec_id']);

                    $goods_Model=new goodsModel();
                    $goods_info=$goods_Model->getOne($val['goods_id']);
                    if(isset($goods_info['salenum'])&&$goods_info['salenum']>=$val['goods_num']){//避免出现负销售量的情况
					    $model_goods->updateGoods(array('salenum'=>array('value'=>$val['goods_num'],'sign'=>'decrease')),$val['goods_id']);
                    }
					//***********更新商品权重***************
					goodsModel::updateGoodsRank($val['goods_id']);
					//**************************
				}
			}
            if($order['store_id']==OFFICIAL_STORE_ID&&$order['is_give_color_plate']==IS_GIVE_COLOR_PLATE_YES){
                Db::update('member',array('is_give_color_plate'=>IS_GIVE_COLOR_PLATE_NO)," member_id='{$order['buyer_id']}'");
            }
            /*检测是否显示现金券红包*/
            memberModel::memberXjqShow($_SESSION['member_id']);
            /*检测是否显示现金券红包*/
		}
		//会员model实例
		$model_member	=new memberModel();
		//卖家信息
		$seller	= $model_member->infoMember(array('member_id'=>$order['seller_id']));
		//确认收货
		if (($state_code == 40)||($state_code ==11) ){
			 $array['order_receipt'] = 1;
			 $array['receipt_time'] = time();
			//更新卖家销量
			$goods_count = 0;
			foreach($goods_list as $value) {
				$goods_count += $value['goods_num'];
			}
			$model_store =new storeModel();
			$update_array = array();
			$update_array['store_sales'] = array('sign'=>'increase','value'=>$goods_count);
			$update_array['store_id'] = $order['store_id']; 
			$model_store->storeUpdate($update_array);

			if (($order['payment_code'] == 'predeposit')){
				//查询买家信息
				$model_member =new memberModel();
				$buyer_info = $model_member->infoMember(array('member_id'=>$_SESSION['member_id']));
				if (!is_array($buyer_info) || count($buyer_info)<=0){
					mobileJump('订单所有者错误','index.php?act=member_order');
				}
				if($order['order_type'] != 2){
					if (floatval($order['order_amount']) > floatval($buyer_info['freeze_predeposit'])){
						mobileJump('预存款冻结金额不足，不能确认收货，如有疑问请联系网站客服','index.php?act=member_order');
					}
				}
				//调整预存款
				$predeposit_model =new predepositModel();
				//卖家增加可用金额
				$log_arr = array();
				$log_arr['memberid'] = $seller['member_id'];
				$log_arr['membername'] = $seller['member_name'];
				$log_arr['logtype'] = '0';
				$log_arr['price'] = $order['order_amount'];//卖家增加可用金额
				$log_arr['desc'] = '订单编号'.$order['order_sn'].'确认收货增加预存款可用金额';
				$predeposit_model->savePredepositLog('order',$log_arr);
				
				logic_orderModel::updateOrderCommissionAndStockFee($order_id);
				//**********减去卖家抽成金额开始************
				logic_orderModel::add_commission($order,$seller,$buyer_info);
				//**********减去卖家抽成金额结束************
				//**********减去卖家仓库管理费开始************
				logic_orderModel::add_stock_fee($order,$seller,$buyer_info);
				//**********减去卖家仓库管理费结束************

				unset($log_arr);
				if($order['order_type'] != 2){
					//买家减少冻结金额
					$log_arr = array();	
					$log_arr['memberid'] = $_SESSION['member_id'];
					$log_arr['membername'] = $_SESSION['member_name'];
					$log_arr['logtype'] = '1';
					$log_arr['price'] = -$order['order_amount'];
					$log_arr['desc'] = '订单编号'.$order['order_sn'].'确认收货减少预存款冻结金额';
					$predeposit_model->savePredepositLog('order',$log_arr);
					unset($log_arr);
				}
			}else{
				//如果平台收款，默认除预存款以外的支付方式都增加到预存款里if (!C('payment'))
				//查询买家信息
				$model_member =new memberModel();
				$buyer_info = $model_member->infoMember(array('member_id'=>$_SESSION['member_id']));
				if (!is_array($buyer_info) || count($buyer_info)<=0){
					showDialog($lang['member_change_order_member_error'],'index.php?act=member&op=order');
				}
				//调整预存款
				$predeposit_model =new predepositModel();
				//卖家增加可用金额
				$log_arr = array();
				$log_arr['memberid'] = $seller['member_id'];
				$log_arr['membername'] = $seller['member_name'];
				$log_arr['logtype'] = '0';
				$log_arr['price'] = $order['order_amount'];//卖家增加可用金额
				$log_arr['desc'] = Language::get('member_change_order_no').$order['order_sn'].Language::get('member_change_ensurereceive_predeposit_logdesc');
				$predeposit_model->savePredepositLog('income',$log_arr);

				logic_orderModel::updateOrderCommissionAndStockFee($order_id);
				//**********减去卖家抽成金额开始************
				logic_orderModel::add_commission($order,$seller,$buyer_info);
				//**********减去卖家抽成金额结束************
				//**********减去卖家仓库管理费开始************
				logic_orderModel::add_stock_fee($order,$seller,$buyer_info);
				//**********减去卖家仓库管理费结束************

			}
		}
		//添加订单日志
		orderModel::addLogOrder($state_code,$order_id,($_GET['state_info1']!=''? $_GET['state_info1'] :$_GET['state_info'] ));
		//更改订单状态
		$model_order->updateOrder($array,$order_id);
		//确认收货时添加会员积分
		if ($GLOBALS['setting_config']['points_isuse'] == 1 && $state_code == 40){
			$points_model =new pointsModel();
			$points_model->savePointsLog('order',array('pl_memberid'=>$_SESSION['member_id'],'pl_membername'=>$_SESSION['member_name'],'orderprice'=>$order['order_amount'],'order_sn'=>$order['order_sn'],'order_id'=>$order['order_id']),true);
		}

		/**
		 * 发送通知
		 */
		$param	= array(
			'site_url'	=> SiteUrl,
			'site_name'	=> $GLOBALS['setting_config']['site_name'],
			'buyer_name'	=> $order['buyer_name'],
			'seller_name'	=> $seller['member_name'],
			'reason'	=> $_GET['state_info1']!=''? $_GET['state_info1'] :$_GET['state_info'],
			'order_sn'	=> $order['order_sn'],
			'order_id'	=> $order['order_id']
		);
		$code	= '';
		switch ($state_type) {
			case 'cancel_order':
				$code	= 'email_toseller_cancel_order_notify';
				break;
			case 'confirm_order':
				$code	= 'email_toseller_finish_notify';
				break;
		}
		noticeModel::system_send_notice($order['seller_id'],$code,$param);

		//货到付款订单额外处理(添加到退货库中,前提是发货了)
		// if(!empty($_GET['paytype']) && trim($_GET['paytype'])=='iscash' && $order ['order_send']!=0){
		// 	orderModel::addCashReturn($order ['order_id']);
		// }

		mobileJump('保存成功',"index.php?act=member_order");
	}


	// 积分礼品订单列表
	public function member_pointorderOp(){

		// 条件
		$condition_arr = array ();
		$condition_arr ['point_buyerid'] = $_SESSION ['member_id'];
		// 分页
		$page = new Page ();
		$page->setEachNum ( 10 );
		$page->setStyle ( 'admin' );
		// 兑换信息列表
		$pointorder_model = new pointorderModel ();
		$order_list = $pointorder_model->getPointOrderList ( $condition_arr, $page, 'simple' );
		$order_idarr = array ();
		$order_listnew = array ();
		if (is_array ( $order_list ) && count ( $order_list ) > 0) {
			foreach ( $order_list as $k => $v ) {
				$order_idarr [] = $v ['point_orderid'];
				$order_listnew [$v ['point_orderid']] = $v;
			}
		}
		// 查询兑换商品
		if (is_array ( $order_idarr ) && count ( $order_idarr ) > 0) {
			$order_idstr = implode ( ',', $order_idarr );
			$prod_list = $pointorder_model->getPointOrderProdList ( array (
					'prod_orderid_in' => $order_idstr 
			), '' );
			if (is_array ( $prod_list ) && count ( $prod_list ) > 0) {
				foreach ( $prod_list as $v ) {
					if (isset ( $order_listnew [$v ['point_orderid']] )) {
						$v ['point_goodsimage'] = ATTACH_POINTPROD . DS . $v ['point_goodsimage'] . '_small.' . get_image_type ( $v ['point_goodsimage'] );
						$order_listnew [$v ['point_orderid']] ['prodlist'] [] = $v;
					}
				}
			}
		}
		Tpl::output ( 'order_list', $order_listnew );
		$this->_assignMobileData($page);
		Tpl::showpage ( 'member_pointorder' );
	}
	
	//积分订单详情
	public function pointOrderDetailOp(){
		$order_id = (int)$_GET['order_id'];
		if($order_id == 0) {
			mobileJump('缺少参数');
		}
		$condition_arr = array ();
		$condition_arr ['point_orderid'] = $order_id;
		$pointorder_model = new pointorderModel ();
		$order_info = $pointorder_model->getPointOrderInfo ($condition_arr);
		if (! is_array ( $order_info ) || count ( $order_info ) <= 0) {
			mobileJump ('订单信息获取失败');
		}
		$order_goods_list = $pointorder_model->getPointOrderProdList (array ('prod_orderid' =>$order_id), '' );
		if (is_array ( $order_goods_list ) && count ( $order_goods_list ) > 0) {
			 foreach ( $order_goods_list as $k=>$v ) {
					 $order_goods_list[$k]['point_goodsimage'] = ATTACH_POINTPROD . DS . $v ['point_goodsimage'] . '_small.' . get_image_type ( $v ['point_goodsimage'] );
			 }
		 }
		$order_info['state_info'] = $this->pointorder_state($order_info['point_orderstate']);
		Tpl::output('order_info',$order_info);
		Tpl::output('order_goods_list',$order_goods_list);
		Tpl::showpage('point_order_detail');
	}
	
	/**
	 * 取消兑换
	 */
	public function cancel_orderOp() {
		$order_id = intval ( $_GET ['order_id'] );
		if ($order_id <= 0) {
			mobileJump('缺少参数');
		}
		$pointorder_model = new pointorderModel ();
		$condition_arr = array ();
		$condition_arr ['point_orderid'] = "$order_id";
		$condition_arr ['point_buyerid'] = $_SESSION ['member_id'];
		$condition_arr ['point_order_enablecancel'] = '1'; // 可取消
		// 查询兑换信息
		$order_info = $pointorder_model->getPointOrderInfo ( $condition_arr, 'simple', 'point_ordersn,point_buyerid,point_buyername,point_allpoint' );
		if (! is_array ( $order_info ) || count ( $order_info ) <= 0) {
			mobileJump ('订单信息获取失败');
		}
		// 更新运费
		$state = $pointorder_model->updatePointOrder ( $condition_arr, array (
				'point_orderstate' => '2' 
		) );
		if ($state) {
			// 退还会员积分
			$points_model = new pointsModel ();
			$insert_arr ['pl_memberid'] = $order_info ['point_buyerid'];
			$insert_arr ['pl_membername'] = $order_info ['point_buyername'];
			$insert_arr ['pl_points'] = $order_info ['point_allpoint'];
			$insert_arr ['point_ordersn'] = $order_info ['point_ordersn'];
			$insert_arr ['pl_desc'] = '取消兑换礼品信息' . $order_info ['point_ordersn'] . '增加积分';
			$points_model->savePointsLog ( 'pointorder', $insert_arr, true );
			// 更改兑换礼品库存
			$prod_list = $pointorder_model->getPointOrderProdList ( array (
					'prod_orderid' => $order_id 
			), '', 'point_goodsid,point_goodsnum' );
			if (is_array ( $prod_list ) && count ( $prod_list ) > 0) {
				$pointprod_model = new pointprodModel ();
				foreach ( $prod_list as $v ) {
					$update_arr = array ();
					$update_arr ['pgoods_storage'] = array (
							'sign' => 'increase',
							'value' => $v ['point_goodsnum'] 
					);
					$update_arr ['pgoods_salenum'] = array (
							'sign' => 'decrease',
							'value' => $v ['point_goodsnum'] 
					);
					$pointprod_model->updatePointProd ( $update_arr, array (
							'pgoods_id' => $v ['point_goodsid'] 
					) );
					unset ( $update_arr );
				}
			}
			mobileJump ('取消兑换成功','index.php?act=member_order&op=member_pointorder' );
		} else {
			mobileJump ( '取消兑换失败');
		}
	}
	/**
	 * 确认收货
	 */
	public function receiving_orderOp() {
		$order_id = intval ( $_GET ['order_id'] );
		if ($order_id <= 0) {
			mobileJump('缺少参数');
		}
		$pointorder_model = new pointorderModel ();
		$condition_arr = array ();
		$condition_arr ['point_orderid'] = "$order_id";
		$condition_arr ['point_buyerid'] = $_SESSION ['member_id'];
		$condition_arr ['point_orderstate'] = '30'; // 待收货
		                                           // 更新运费
		$state = $pointorder_model->updatePointOrder ( $condition_arr, array (
				'point_orderstate' => '40',
				'point_finnshedtime' => time () 
		) );
		if ($state) {
			mobileJump ('确认收货成功','index.php?act=member_order&op=member_pointorder' );
		} else {
			mobileJump ('确认收货失败');
		}
	}
}
